package com.hnkywl.sts.action.jhgl;

import com.hnkywl.sts.entity.jhgl.Bgjhhz;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.entity.sys.Gncz;
import com.hnkywl.sts.service.jhgl.BgjhhzService;
import com.hnkywl.sts.service.jhgl.BgjhhzmxService;
import com.hnkywl.sts.service.kcgl.ZkdService;
import com.hnkywl.sts.service.organ.NbgsService;
import com.hnkywl.sts.service.sys.GnczService;
import com.hnkywl.sts.service.sys.WzbmService;
import com.hnkywl.sts.webservice.bg.request.SendPlanImportResult;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ZHUCHG
 * Date: 13-6-3
 * Time: 下午8:09
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/jhgl/bgjhywk")
public class BgjhywkAction extends SimpleActionSupport {
    //汇总ID
    private Long hzid;
    //明细ID
    private Long mxid;

    private int status;

    private Date date;
    //总公司
    private Nbgs zgs;
    //保供计划单位Id
    private Long jhdwId;
    //物资大类
    private String wzdl;
    //计划年份
    private Integer jhnf;
    //计划月份
    private Integer jhyf;

    private Date startDate;

    private Date endDate;
    //物资编码
    private String wzbm;
    //计划说明
    private String sm;
    //分页组件 起始位置
    private int page;
    //分页组件 页面大小
    private int rows;
    //保供计划汇总
    private Bgjhhz bgjhhz;
    //保供计划汇总明细
    private Bgjhhzmx bgjhhzmx;

    private List<Bgjhhzmx> bgjhhzmxList;

    private NbgsService nbgsService;
    private BgjhhzService bgjhhzService;
    private BgjhhzmxService bgjhhzmxService;
    //设备材料
    private String ywksbcl;
    //功能操作
    private List<Gncz> gnczList;
    private GnczService gnczService;
    private ZkdService zkdService;
    private Long zkdId;
    // 物资编码service
    private WzbmService wzbmService;
    private String ckIds;
    private Long dhckId;
    private String khIds;
    private String dhrq;
    private String phsls;
    private SendPlanImport sendPlanImport;

    private Long bgjhhzmxId;


    @Action("bgjhywk")
    public String bgjhywk() {
        date = new Date();
        List<Nbgs> roots = nbgsService.findAllRootNbgs();
        if (!CollectionUtils.isEmpty(roots))
            zgs = roots.get(0);
        gnczList = gnczService.findGnczByJsAndUrl(request.getServletPath());
        return SUCCESS;
    }

    @Action("bgjhywkList")
    public void bgjhywkList() {
        if (startDate != null)
            startDate = convertDate(startDate, true);
        if (endDate != null)
            endDate = convertDate(endDate, false);
        renderJson(bgjhhzmxService.findYwkList(status, jhdwId, wzdl, jhnf, jhyf, startDate, endDate, wzbm, sm, ywksbcl, page, rows));
    }

    @Action("bgjhywk_yq")
    public String bgjhywk_yq() {
        bgjhhzmx = bgjhhzmxService.find(mxid);
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        dhrq = simple.format(bgjhhzmx.getDhrq());
        return SUCCESS;
    }

    //计划延期
    @Action("ywk_jhyq")
    public void ywk_jhyq() {
        try {
            this.bgjhhzmxService.saveJhyq(bgjhhzmx);
            renderText("{\"statusCode\":\"200\",\"message\":\"计划延期成功！\"}");
        } catch (RuntimeException e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    //业务科二级平衡
    @Action("ywkejph")
    public String ywkejph() {
        bgjhhzmx = bgjhhzmxService.find(mxid);
        return SUCCESS;
    }

    //二级平衡库存
    @Action("ejphkc")
    public void ejphkc() {
        renderJson(bgjhhzmxService.findKcByBjjhhzmx(mxid));
    }

    //二级平衡转库
    @Action("ejphzk")
    public void ejphzk() {
        try {
            zkdService.ejphzk(ckIds, khIds, phsls, dhckId, bgjhhzmxId);
            renderText("{\"statusCode\":\"200\", \"message\":\"保存保供物资转库成功!\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    @Action("ywkcl")
    public void ywkcl() {
        if (bgjhhzmxList == null && bgjhhzmxList.size() == 0) {
            renderJson("{\"statusCode\":\"300\", \"message\":\"计划为空!\"}");
            return;
        }
        // 把数据发送给保供接口
        List<Bgjhhzmx> jkData = new ArrayList<Bgjhhzmx>();
        try {
            //业务科处理数据
            List<Bgjhhzmx> ywkclData = new ArrayList<Bgjhhzmx>();
            for (Bgjhhzmx mx : bgjhhzmxList) {
                List<Bgjhhzmx> temp = new ArrayList<Bgjhhzmx>();
                temp.add(mx);
                if (StringUtils.isNotEmpty(mx.getThyy())) {
                    bgjhhzmxService.ywkth(temp);
                } else {
                    bgjhhzmxService.ywkcl(temp);
                    ywkclData.addAll(temp);
                }
                bgjhhzService.ywkclwc(mx.getBgjhhz().getId());
            }
            //接口数据准备
            for (Bgjhhzmx bx : ywkclData) {
                //采购方式为比价并且业务处理，不包括退回
                if (bx.getCgfs() == 1 && bx.getZt() == 4) {
                    if (null == bx.getBgjhhz().getJhdw()) {
                        // 查询计划单位
                        Gsjg gsjg = this.bgjhhzService.getJhdwByBgjhhz(bx.getBgjhhz().getId());
                        if (null != gsjg) {
                            bx.getBgjhhz().setJhdw(gsjg);
                        }
                    }
                    if (null != bx.getWzgg().getCode()) {
                        // 查询保供物资编码
                        String wzCode = this.wzbmService.findWzbmByCode(bx.getWzgg().getCode());
                        bx.getWzgg().setCode(wzCode);
                    }
                    jkData.add(bx);
                }
            }
            //接口数据发送
            if (!jkData.isEmpty()) {
                bgjhhzService.updateKsdr(jkData);
                List<SendPlanImportResult> resultList = sendPlanImport.sendDataBg(jkData,"");
                // 判断数据是否处理成功 resultList就一条数据并且errornumber为200则全部处理成功,否则部分处理成功
                if(!CollectionUtils.isEmpty(resultList)){
                    if (resultList.get(0).getErrorNumber().equals("200")) {
                        bgjhhzService.updateSfcg(jkData,resultList);
                        renderJson("{\"statusCode\":\"200\", \"message\":\"操作成功!\"}");
                    } else {
                        bgjhhzService.updateSfcg(jkData,resultList);
                        renderJson("{\"statusCode\":\"301\", \"message\":\"处理完成但编号为"+net.ruixin.utils.CollectionUtils.fetchPropertyToString(resultList,"detailId",",")+"的计划导入失败，12小时以内系统自动导入，或查询未导入成功的计划再次处理!\"}");
                    }
                } else {
                    bgjhhzService.dealWhenExcept(jkData,"调用接口异常，到日志查看异常信息！");
                    renderJson("{\"statusCode\":\"300\", \"message\":\"操作失败!\"}");
                }
            } else {
                renderJson("{\"statusCode\":\"200\", \"message\":\"操作成功!\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //产生异常，所有数据置为"业务科已处理状态"
            bgjhhzService.dealWhenExcept(jkData,e.getMessage());
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * @param date
     * @param flag true:当天00:00:00   false:第二天00:00:00
     * @return
     */
    private Date convertDate(Date date, boolean flag) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        if (!flag)
            gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.HOUR, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        return gc.getTime();
    }



    //=================setter,getter===================
    public Long getHzid() {
        return hzid;
    }

    public void setHzid(Long hzid) {
        this.hzid = hzid;
    }

    public Long getMxid() {
        return mxid;
    }

    public void setMxid(Long mxid) {
        this.mxid = mxid;
    }

    public Bgjhhz getBgjhhz() {
        return bgjhhz;
    }

    public void setBgjhhz(Bgjhhz bgjhhz) {
        this.bgjhhz = bgjhhz;
    }

    public void setBgjhhzmx(Bgjhhzmx bgjhhzmx) {
        this.bgjhhzmx = bgjhhzmx;
    }

    public List<Bgjhhzmx> getBgjhhzmxList() {
        return bgjhhzmxList;
    }

    public void setBgjhhzmxList(List<Bgjhhzmx> bgjhhzmxList) {
        this.bgjhhzmxList = bgjhhzmxList;
    }

    //===================getter=====================

    public Date getDate() {
        return date;
    }

    public Nbgs getZgs() {
        return zgs;
    }

    public Bgjhhzmx getBgjhhzmx() {
        return bgjhhzmx;
    }

    public List<Gncz> getGnczList() {
        return gnczList;
    }

    //===================setter=====================


    public Long getZkdId() {
        return zkdId;
    }

    public void setZkdId(Long zkdId) {
        this.zkdId = zkdId;
    }

    public Long getDhckId() {
        return dhckId;
    }

    public void setDhckId(Long dhckId) {
        this.dhckId = dhckId;
    }

    public String getCkIds() {
        return ckIds;
    }

    public void setCkIds(String ckIds) {
        this.ckIds = ckIds;
    }

    public String getKhIds() {
        return khIds;
    }

    public void setKhIds(String khIds) {
        this.khIds = khIds;
    }

    public String getPhsls() {
        return phsls;
    }

    public void setPhsls(String phsls) {
        this.phsls = phsls;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public void setZgs(Nbgs zgs) {
        this.zgs = zgs;
    }

    public void setJhdwId(Long jhdwId) {
        this.jhdwId = jhdwId;
    }

    public void setWzdl(String wzdl) {
        this.wzdl = wzdl;
    }

    public void setJhnf(Integer jhnf) {
        this.jhnf = jhnf;
    }

    public void setJhyf(Integer jhyf) {
        this.jhyf = jhyf;
    }

    public void setWzbm(String wzbm) {
        this.wzbm = wzbm;
    }

    public void setSm(String sm) {
        this.sm = sm;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getYwksbcl() {
        return ywksbcl;
    }

    public void setYwksbcl(String ywksbcl) {
        this.ywksbcl = ywksbcl;
    }

    public String getDhrq() {
        return dhrq;
    }

    public void setDhrq(String dhrq) {
        this.dhrq = dhrq;
    }

    public Long getBgjhhzmxId() {
        return bgjhhzmxId;
    }

    public void setBgjhhzmxId(Long bgjhhzmxId) {
        this.bgjhhzmxId = bgjhhzmxId;
    }

    @Autowired
    public void setNbgsService(NbgsService nbgsService) {
        this.nbgsService = nbgsService;
    }

    @Autowired
    public void setBgjhhzService(BgjhhzService bgjhhzService) {
        this.bgjhhzService = bgjhhzService;
    }

    @Autowired
    public void setBgjhhzmxService(BgjhhzmxService bgjhhzmxService) {
        this.bgjhhzmxService = bgjhhzmxService;
    }

    @Autowired
    public void setGnczService(GnczService gnczService) {
        this.gnczService = gnczService;
    }

    @Autowired
    public void setWzbmService(WzbmService wzbmService) {
        this.wzbmService = wzbmService;
    }

    @Autowired
    public void setSendPlanImport(SendPlanImport sendPlanImport) {
        this.sendPlanImport = sendPlanImport;
    }

    @Autowired
    public void setZkdService(ZkdService zkdService) {
        this.zkdService = zkdService;
    }
}
